package DownloadImg;

import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DownLoadImage02 {

    private static final int THREAD_POOL_SIZE = 10; // 可以根据实际情况调整线程池大小

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

        try {
            // 读取文件中的URL
            URL urls = DownLoadImage02.class.getClassLoader().getResource("images-url.txt");
            InputStream is = urls.openStream();
            String line;
            while ((line = getLine(is)) != null) {
                final String imageUrl = line.trim();
                executor.execute(new DownloadTask(imageUrl));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.MINUTES)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException ex) {
                executor.shutdownNow();
            }
        }
    }

    private static String getLine(InputStream is) {
        // 实现读取文件并返回每一行数据的逻辑
        // ...
        return null; // 返回读取到的行
    }

    static class DownloadTask implements Runnable {
        private String imageUrl;

        public DownloadTask(String imageUrl) {
            this.imageUrl = imageUrl;
        }

        @Override
        public void run() {
            try {
                URL url = new URL(imageUrl);
                InputStream is = url.openStream();
                String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
                OutputStream os = new FileOutputStream("downloaded-images/" + fileName);
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                is.close();
                System.out.println(imageUrl + " downloaded.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}